package com.ruoyi.common.websocket.handler;

import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.JSONUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractWebsocketMsgHandler implements WebsocketMsgHandler {
	private static Map<String, String> cache = new HashMap<String, String>();
	
	/**
	 * 取得一定长度的随机数
	 * 
	 * @param length
	 * @return
	 */
	public static Integer getRandomNum(int length) {
		StringBuilder stringBuilder = new StringBuilder();
		for (int j = 0; j < length; j++) {
			stringBuilder.append((int) (Math.random() * 9));
		}
		return Integer.parseInt(stringBuilder.toString());
	}
	
	public static JSONObject getCommandTemplate(String id, Map<String, Object> param) {
		String text = getCommandTemplate(id);
		JSONObject res = replace(text, param);
		return res;
	}

	private static JSONObject replace(String text, Map<String, Object> param) {
		Set<Entry<String, Object>> entries = param.entrySet();
		for (Entry<String, Object> entry : entries) {
			Object value = entry.getValue();
			if(value == null) {
				value = "";
			}
			String key = "${" + entry.getKey() + "}";
			if(value instanceof Map || value instanceof Collection) {
				text = text.replace(key, JSONUtil.toJSONString(value));
			}else {
				text = text.replace(key, value.toString());
			}
			
		}
		//JSONObject res = JSON.parseObject(text);
		JSONObject res = JSONUtil.parseObject(text);
		return res;
	}

	private static String getCommandTemplate(String id) {
		String cacheValue = cache.get(id);
		if(StringUtils.isNotBlank(cacheValue)) {
			return cacheValue;
		}
		String text = null;
		InputStream in = AbstractWebsocketMsgHandler.class.getResourceAsStream("/config/command.xml");
		try {
			SAXReader reader = new SAXReader();
			Document document = reader.read(in);
			Element root = document.getRootElement();
			List<Element> commands = root.elements();
			Element command = getElementById(id, commands);
			if (command != null) {
				text = command.getText().trim();
				cache.put(id, text);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				IOUtils.closeQuietly(in);
			}
		}
		return text;
	}

	private static Element getElementById(String id, List<Element> elements) {
		if (elements != null && elements.size() > 0) {
			for (Element element : elements) {
				Attribute idAttr = element.attribute("id");
				if (idAttr != null) {
					String value = idAttr.getValue();
					if (value.equals(id)) {
						return element;
					}
				}
			}
		}
		return null;
	}
}
